#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/socket.h>

#define PORT 8080
#define BUFFER_SIZE 1024
#define BACKLOG 5

void handle_client(int connfd, struct sockaddr_in client_addr) {
    char buffer[BUFFER_SIZE];
    ssize_t n;
    
    printf("客户端 %s:%d 已连接\n", 
           inet_ntoa(client_addr.sin_addr), 
           ntohs(client_addr.sin_port));
    
    // 接收和处理数据
    while ((n = read(connfd, buffer, sizeof(buffer) - 1)) > 0) {
        buffer[n] = '\0';
        printf("收到来自 %s:%d 的消息: %s\n", 
               inet_ntoa(client_addr.sin_addr),
               ntohs(client_addr.sin_port),
               buffer);
        
        // 处理请求（这里简单回显）
        char response[BUFFER_SIZE];
        snprintf(response, sizeof(response), "服务器已收到: %s", buffer);
        
        // 发送响应
        if (write(connfd, response, strlen(response)) < 0) {
            perror("write error");
            break;
        }
        printf("已发送响应给客户端\n");
    }
    
    if (n == 0) {
        printf("客户端 %s:%d 关闭了连接\n",
               inet_ntoa(client_addr.sin_addr),
               ntohs(client_addr.sin_port));
    } else if (n < 0) {
        perror("read error");
    }
    
    close(connfd);
    printf("连接已关闭\n\n");
}

//char buffer[] = "Hello World";
//char response[100];

//snprintf(response, sizeof(response), "服务器已收到: %s", buffer);
//response的内容变为: "服务器已收到: Hello World"

int main() {
    int listenfd, connfd;
    struct sockaddr_in serv_addr, client_addr;
    socklen_t client_len = sizeof(client_addr);
    
    // 1. 创建socket
    if ((listenfd = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
        perror("socket creation failed");
        exit(EXIT_FAILURE);
    }
    printf("Socket创建成功\n");
    
    // 设置SO_REUSEADDR选项，避免地址占用错误
    int opt = 1;
    if (setsockopt(listenfd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt))) {
        perror("setsockopt failed");
        close(listenfd);
        exit(EXIT_FAILURE);
    }
    
    // 2. 绑定地址和端口
    memset(&serv_addr, 0, sizeof(serv_addr));
    serv_addr.sin_family = AF_INET;
    serv_addr.sin_addr.s_addr = INADDR_ANY;
    serv_addr.sin_port = htons(PORT);
    
    if (bind(listenfd, (struct sockaddr*)&serv_addr, sizeof(serv_addr)) < 0) {
        perror("bind failed");
        close(listenfd);
        exit(EXIT_FAILURE);
    }
    printf("绑定端口 %d 成功\n", PORT);
    
    // 3. 开始监听
    if (listen(listenfd, BACKLOG) < 0) {
        perror("listen failed");
        close(listenfd);
        exit(EXIT_FAILURE);
    }
    printf("开始监听，等待客户端连接...\n\n");
    
    // 4. 接受和处理客户端连接
    while (1) {
        if ((connfd = accept(listenfd, (struct sockaddr*)&client_addr, &client_len)) < 0) {
            perror("accept failed");
            continue;
        }
        
        // 处理客户端连接（这里使用阻塞方式，实际应用中可用多线程或IO多路复用）
        handle_client(connfd, client_addr);
    }
    
    close(listenfd);
    return 0;
}